from django.contrib.gis.db import models
from urllib2 import urlopen
from uuid import uuid1 as uuid
from datetime import datetime 
 
class OnlineResource(models.Model):
    """ A target for a webservice to look for metadata. 

    >>> c = CrawlerTarget(url=TEST_WMS_CAPABILITIES,format='WMS')
    """
    __module__ = 'duetopia.register.models'
    url = models.CharField(max_length=255)
    format =  models.CharField(max_length=255)
    protocol = models.CharField(max_length=16)
    last_etag = models.DateTimeField()
    last_visited = models.DateTimeField()
    last_modified = models.DateTimeField()
    last_status = models.IntegerField(default=0)
    index = models.IntegerField()
    interval = models.IntegerField()
    body = models.TextField()

    def visit(self):
        try:
            r = urlopen(self.url)
            self.last_status = r.code

            mod = r.headers.getheader('Last-Modified')
            if mod is not None: self.last_modified = mod
            etag = r.headers.getheader('ETag')
            if etag is not None: self.last_etag = etag 
     
            self.last_visited = datetime.now()
            return r.read()
        except:
            return None 
    
   
class SearchResult(models.Model):
    """ A cache of a search run against our db
    - see views/opensearch.py for main use case + reasoning
    """
    __module__ = 'duetopia.register.models'
    query = models.CharField(max_length=255)
    result_count = models.IntegerField()
    uuid = models.CharField(max_length=255)
    last_modified = models.DateTimeField()
 
    def save(self):
        if self.uuid is None:
            self.uuid = uuid().urn
        super(SearchResult, self).save()
